package com.kefu.admin.common.zk.zkleader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.support.ScheduledMethodRunnable;

import java.lang.reflect.Method;

/**
 * Created by TWD on 2018/9/29.
 */
public class ZkScheduledMethodRunnable  extends ScheduledMethodRunnable {

    private static final Logger logger = LoggerFactory.getLogger(ZkScheduledMethodRunnable.class);
    private ZkSchedulerCoordinator zkSchedulerCoordinator;
    private String name;
    private ZkScheduledMethodRunnable.ZkSchedulerJobHandler jobHandler = new ZkScheduledMethodRunnable.ZkSchedulerJobHandler(this);

    public ZkScheduledMethodRunnable(Object target, Method method, ZkSchedulerCoordinator zkSchedulerCoordinator) {
        super(target, method);
        this.zkSchedulerCoordinator = zkSchedulerCoordinator;
        this.name = String.format("Class: %s, method: %s",target.getClass().getName(), method.getName());
    }

    public ZkScheduledMethodRunnable(Object target, String methodName) throws NoSuchMethodException {
        super(target, methodName);
    }

    public void run() {
        if(this.zkSchedulerCoordinator.isLeader()) {
            try {
                //logger.info("**************"+this.zkSchedulerCoordinator.isLeader());
                this.jobHandler.doExecute(new String[0]);
            } catch (Throwable var2) {
                throw new RuntimeException(var2);
            }
        }

    }

    public void superRun() {
        super.run();
    }
    /****/
    class ZkSchedulerJobHandler {
        ZkScheduledMethodRunnable zkScheduledMethodRunnable;

        public ZkSchedulerJobHandler(ZkScheduledMethodRunnable zkScheduledMethodRunnable) {
            this.zkScheduledMethodRunnable = zkScheduledMethodRunnable;
        }

        protected String getJobName() {
            return this.zkScheduledMethodRunnable.name;
        }

        protected boolean needZkLock() {
            return false;
        }

        protected void doExecute(String[] params) throws Exception {
            this.zkScheduledMethodRunnable.superRun();
        }
    }

}
